from flask import g, jsonify
from app.libs.error_code import SuccessLike
from app.libs.redprint import Redprint
from app.libs.token_auth import auth
from app.models.blogs import Like, Comment, Blog
from flask import request
from app.forms.blogs import LikeForm, CommentForm
from app.models.base import db
#TODO 展示博客详情 点赞博客√ 评论博客√ 收藏博客 分享博客


red_blogs = Redprint('blogs')


@red_blogs.route('/blogs/detail')
def bloge_detail():
    pass


@red_blogs.route('/like')
@auth.login_required
def like():
    '''
        校验:
            1.判断操作类型
            2.判断博客是否存在
        逻辑:
            1.add操作类型添加点赞对象,将博客总赞数+1/n rm操作类型删除点赞对象,将博客总赞数-1
            2.返回成功
    '''
    form = LikeForm(request.json)
    form.validate_for_api()
    like = Like()
    if form.is_like.data == 'add':
        like.add_like(form.data)
    else:
        like.delect_like(form.data)
    return SuccessLike()


@red_blogs.route('/comment')
@auth.login_required
def comment():
    '''
        接受 博客id 评论内容 父评论id uid
        校验 content not none and blogs_id not none
        处理 新增对象
        返回 success
    '''
    form = CommentForm(request.json)
    form.validate_for_api()
    with db.auto_commit():
        comment = Comment()
        comment.blogs_id = form.blogs_id.data
        comment.content = form.content.data
        comment.user_id = g.user.uid
        comment.parent_id = form.parent_id.data
        db.session.add(comment)
    return jsonify(comment)
